package com.nodecollege.cloud.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.exception.UpmsException;
import com.nodecollege.cloud.common.model.BindVO;
import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.QueryRelationVO;
import com.nodecollege.cloud.common.model.po.UpmsMember;
import com.nodecollege.cloud.common.model.po.UpmsOrg;
import com.nodecollege.cloud.common.model.po.UpmsOrgMember;
import com.nodecollege.cloud.common.utils.NCUtils;
import com.nodecollege.cloud.dao.mapper.UpmsMemberMapper;
import com.nodecollege.cloud.dao.mapper.UpmsOrgMapper;
import com.nodecollege.cloud.dao.mapper.UpmsOrgMemberMapper;
import com.nodecollege.cloud.service.OrgMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LC
 * @date 2020/1/5 20:37
 */
@Service
public class OrgMemberServiceImpl implements OrgMemberService {

    @Autowired
    private UpmsOrgMemberMapper upmsOrgMemberMapper;

    @Autowired
    private UpmsOrgMapper upmsOrgMapper;

    @Autowired
    private UpmsMemberMapper upmsMemberMapper;

    /**
     * 根据成员信息查询组织机构信息
     *
     * @param query
     * @return
     */
    @Override
    public NCResult<UpmsOrg> getOrgListByMemberId(QueryRelationVO<UpmsOrg, UpmsMember> query) {
        NCUtils.nullOrEmptyThrow(query.getEndNode().getMemberId(), new UpmsException("", "成员id不能为空！"));
        List<UpmsOrg> list = new ArrayList<>();
        Long total = 0L;
        if (NCConstants.INT_NEGATIVE_1.equals(query.getPageSize())) {
            list = upmsOrgMapper.selectOrgListJoinOrgMember(query.toMap());
            total = NCUtils.isNullOrEmpty(list) ? 0 : Long.parseLong(list.size() + "");
        } else {
            Page page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
            if (query.isSort()) {
                page.setOrderBy(query.getSortKey() + " " + query.getSortDirection());
            }
            list = upmsOrgMapper.selectOrgListJoinOrgMember(query.toMap());
            total = page.getTotal();
        }
        return NCResult.ok(list, total);
    }

    /**
     * 根据组织机构id查询成员信息
     *
     * @param query
     * @return
     */
    @Override
    public NCResult<UpmsMember> getMemberListByOrgId(QueryRelationVO<UpmsOrg, UpmsMember> query) {
        NCUtils.nullOrEmptyThrow(query.getStartNode().getOrgId(), new UpmsException("", "组织机构id不能为空！"));
        List<UpmsMember> list = new ArrayList<>();
        Long total = 0L;
        if (NCConstants.INT_NEGATIVE_1.equals(query.getPageSize())) {
            list = upmsMemberMapper.selectMemberListJoinOrgMember(query.toMap());
            total = NCUtils.isNullOrEmpty(list) ? 0 : Long.parseLong(list.size() + "");
        } else {
            Page page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
            if (query.isSort()) {
                page.setOrderBy(query.getSortKey() + " " + query.getSortDirection());
            }
            list = upmsMemberMapper.selectMemberListJoinOrgMember(query.toMap());
            total = page.getTotal();
        }
        return NCResult.ok(list, total);
    }

    /**
     * 绑定解绑组织机构成员信息
     *
     * @param bindVO
     */
    @Override
    public void bindOrgMember(BindVO bindVO) {
        NCUtils.nullOrEmptyThrow(bindVO.getMainSource(), new UpmsException("-1", "参数错误！"));

        // 已绑定的数据
        UpmsOrgMember query = new UpmsOrgMember();
        query.setTenantId(bindVO.getTenantId());
        // 最终保留的数据
        List<UpmsOrgMember> endList = new ArrayList<>();
        if (bindVO.getMainSource()) {
            NCUtils.nullOrEmptyThrow(bindVO.getSourceIds(), new UpmsException("-1", "绑定入参有误"));
            query.setOrgId(bindVO.getSourceIds().get(0));
            bindVO.getSourceIds().forEach(orgId -> {
                bindVO.getTargetIds().forEach(memberId -> {
                    UpmsOrgMember end = new UpmsOrgMember();
                    end.setMemberId(memberId);
                    end.setOrgId(orgId);
                    end.setTenantId(bindVO.getTenantId());
                    endList.add(end);
                });
            });
        } else {
            NCUtils.nullOrEmptyThrow(bindVO.getTargetIds(), new UpmsException("-1", "绑定入参有误！"));
            NCUtils.nullOrEmptyThrow(bindVO.getSourceIds(), new UpmsException("-1", "成员必须至少属于一个组织！"));
            query.setMemberId(bindVO.getTargetIds().get(0));
            bindVO.getTargetIds().forEach(memberId -> {
                bindVO.getSourceIds().forEach(orgId -> {
                    UpmsOrgMember end = new UpmsOrgMember();
                    end.setMemberId(memberId);
                    end.setOrgId(orgId);
                    end.setTenantId(bindVO.getTenantId());
                    endList.add(end);
                });
            });
        }
        List<UpmsOrgMember> exList = upmsOrgMemberMapper.selectListByOrgMember(query);

        // 取消绑定的数据
        exList.forEach(ex -> {
            Boolean delFlag = true;
            for (int i = 0; i < endList.size(); i++) {
                if (ex.getOrgId().equals(endList.get(i).getOrgId())
                        && ex.getMemberId().equals(endList.get(i).getMemberId())) {
                    delFlag = false;
                    break;
                }
            }
            if (delFlag) {
                upmsOrgMemberMapper.deleteByPrimaryKey(ex.getOrgMemberId());
            }
        });

        // 新增绑定的数据
        endList.forEach(end -> {
            Boolean addFlag = true;
            for (int i = 0; i < exList.size(); i++) {
                if (end.getOrgId().equals(exList.get(i).getOrgId())
                        && end.getMemberId().equals(exList.get(i).getMemberId())) {
                    addFlag = false;
                    break;
                }
            }
            if (addFlag) {
                upmsOrgMemberMapper.insert(end);
            }
        });
    }
}
